package com.ssm.user.delayQueue;
import com.alibaba.druid.support.json.JSONUtils;
import com.ssm.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MassMailTaskService {
    @Resource
    private RedisUtil redisUtil;

    // 该MassMailTaskService类位于Redis中ZSet结构的key
    private static final String MASS_MAIL_TASK_KEY = "massMailTask";

    public void pushMassMailTaskQueue(MassMailTask massMailTask) { //入队,推送延迟任务
        Date startTime = massMailTask.getStartTime();
        if(startTime == null) {
            return;
        }

        if(startTime.compareTo(new Date()) <= 0) { //开始时间小于等于当前时间,也不处理(compareTo比大小，小于为-1 等于为0)
            return;
        }

        log.info("定时任务加入队列, massTask:{}", massMailTask);

        //有序集合 Zadd key score1 member1 [score2 member2]
        redisUtil.zAdd(MASS_MAIL_TASK_KEY,  //key
                massMailTask.getTaskId().toString(), //value为id
                startTime.getTime() //score为当前任务开始时间的毫秒数
        );
    }

    public Set<Long> poolMassTaskQueue() { //出队，拉取延迟任务
        //获取有序集合中指定分数范围内的元素(zset默认有序)
        Set<String> taskIdSet = redisUtil.rangeByScore(MASS_MAIL_TASK_KEY, 0, System.currentTimeMillis());

        if(CollectionUtils.isEmpty(taskIdSet)) {
            return Collections.emptySet();
        }

        //此时已得到所有要执行的定时任务了，把zset中的任务remove
        redisUtil.removeZsetList(MASS_MAIL_TASK_KEY, taskIdSet);

        //转为Long类型set
        return taskIdSet.stream().map(n -> Long.parseLong(n)).collect(Collectors.toSet());
    }
}
